package com.social.servlet;

import com.social.dao.FriendDAO;
import com.social.dao.UserDAO;
import com.social.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/AddFriendServlet")
public class AddFriendServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        // 获取参数（注意处理中文乱码）
        request.setCharacterEncoding("UTF-8");
        String friendNickname = request.getParameter("friendNickname");

        UserDAO userDAO = new UserDAO();
        User friend = userDAO.getUserByNickname(friendNickname);
        
        if (friend != null) {
            FriendDAO friendDAO = new FriendDAO();
            try {
                friendDAO.addFriendRequest(user.getId(), friend.getId());
                response.sendRedirect("addFriend.jsp?success=1");
            } catch (Exception e) {
                e.printStackTrace(); // 打印日志方便排查
                response.sendRedirect("addFriend.jsp?error=2"); // 数据库操作失败
            }
        } else {
            response.sendRedirect("addFriend.jsp?error=1"); // 用户不存在
        }
    }
    @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.sendRedirect("addFriend.jsp"); // 重定向到添加好友的页面
}
}